package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/06/18 10:12
 */
@Service
public class AccountServiceImpl implements AccountService{
    @Autowired
    AccountMapper accountMapper;

    /*@Autowired
    TransactionTemplate transactionTemplate;*/

    //@Transactional(readOnly = true)
    @Transactional(timeout = 5,noRollbackFor = ArithmeticException.class)
    @Override
    public void transfer(int fromId, int destId, Integer money) {
        // 查询现有的money是多少
        Integer fromMoney = accountMapper.select(fromId);
        Integer destMoney = accountMapper.select(destId);

        // 计算转账后的money是多少
        fromMoney -= money;
        destMoney += money;

        //transactionTemplate.execute(new TransferTransactionCallBack(accountMapper,fromId,destId,fromMoney,destMoney));
        /*Integer finalFromMoney = fromMoney;
        Integer finalDestMoney = destMoney;
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                // 更新money
                int update1 = accountMapper.update(fromId, finalFromMoney);
                int i = 1 / 0;
                int update2 = accountMapper.update(destId, finalDestMoney);
                return null;
            }
        });*/
        // 更新money
        int update1 = accountMapper.update(fromId, fromMoney);
        int i = 1 / 0;
        int update2 = accountMapper.update(destId, destMoney);

    }
}
